import React , { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { inject, observer } from 'mobx-react';
import { toJS, observe } from 'mobx';
import { asyncComponent } from 'react-async-component';
import { withRouter, Route, Link } from 'react-router-dom';
import { WhiteSpace, Icon, Badge, Popover } from 'weaver-mobile';
import { TabPage, RouteLayout, Share } from 'weaver-mobile-page';
import ReqNoRight from './ReqNoRight';
import Prompt from './prompt/index';
import SecondAuthInfo from "./prompt/SecondAuthInfo";
import RemindType from './hoverRoute/remind/RemindType';
import ReqWffileUpload from './hoverRoute/reqWfFileUpload/index';
import BottomOperate from './operate/index';
import MainLayout from './layout/MainLayout';
import SignList from './signList/async';
import Communicate from './communicate/async';
import ReqImport from './operate/ReqImport';
import ReqDing from './operate/ReqDing';
import FreeWorkflowSimple from './freeWorkflowSimple/index';
import OdocPage from './odocPage/index';
import SecondAuthDialog from "../components/secondauth/index";
import * as Common from '../util/common';
import * as ForwardPage from '../util/forwardPage';
import { _, src, DetailUtil, InvoiceUtil } from '../util/pcPublic';
import FieldEntity from '../stores/FieldEntity';
import * as EmSDK from '../util/emSDK';
import * as FormUtil from '../util/formUtil';
import * as AsyncUtil from '../util/asyncLoad'
import { calcReqMainPaadingBottom, loadMoreSign } from '../util/SignUtil';
import * as API_REQ from '../apis/form';
import base from './../util/base'
import * as authTypes from "../constants/secondAuthType";
import { openAuthDetail } from "../util/secondAuthUtil";
import '../util/rightBtn';
import '../util/submit';
import '../util/windowFun';
import ContinuationProcess from './ContinuationProcess';
import WfHelpefulTipContent  from './cellType/wf-helpful-tip/index'
import CusSignInputNew from "../components/layout/CusSignInputNew";

if (!window.OdocRightBtn) {
    import("../../odoc/OdocRightBtn").then(m => {
        const { OdocRightBtn } = m;
        OdocRightBtn.setBase(base);
        window.OdocRightBtn = OdocRightBtn;
    })
}

const getLabel = Common.getLabel;
const jQuery = window.jQuery;
const coms = {
    EditDetailRow: asyncComponent({
        resolve: () => import("./hoverRoute/EditDetailRow")
    }),
    Picture: asyncComponent({
        resolve: () => import("./hoverRoute/Picture")
    }),
    Status: asyncComponent({
        resolve: () => import("./hoverRoute/Status")
    }),
    Resource: asyncComponent({
        resolve: () => import("./hoverRoute/Resource")
    }),
    EhOperator: asyncComponent({
        resolve: () => import("./hoverRoute/EhOperator")
    }),
    RejectChoose: asyncComponent({
        resolve: () => import("./hoverRoute/rejectChoose/RejectChoose")
    }),
    ForwardBack: asyncComponent({
        resolve: () => import("./hoverRoute/ForwardBack")
    }),
    SignAnnexList: asyncComponent({
        resolve: () => import("./hoverRoute/sign/AnnexList")
    }),
    SignSoundList: asyncComponent({
        resolve: () => import('./hoverRoute/sign/SoundList')
    }),
    SignFormAnnotationList: asyncComponent({
        resolve: () => import('./hoverRoute/sign/FormAnnotationList')
    }),
    NextNodeOperator: asyncComponent({
        resolve: () => import('./hoverRoute/nextNodeOperator')
    }),
    LocationMap: asyncComponent({
        resolve: () => import('./hoverRoute/locationMap')
    }),
    Map: asyncComponent({
        resolve: () => import('./hoverRoute/Map')
    }),
    Intervenor: asyncComponent({
        resolve: () => import('./hoverRoute/intervenor')
    }),
    FnaInvoiceScanning: asyncComponent({//财务发票扫描
        resolve: () => import('../../public/fna/fnaInvoiceScanning/index')
    }),
    SecondAuthDetail: asyncComponent({
        resolve: () => import("./hoverRoute/secondAuthDetail")
    }),
    ConfirmReminder: asyncComponent({
        resolve: () => import("./hoverRoute/remind/ConfirmReminder")
    }),
    FollowList: asyncComponent({
        resolve: () => import("../../workflow/components/follow/index")
    }),
    TagManage: asyncComponent({
        resolve: () => import("../../workflow/components/follow/tagManage")
    }),
    TagEdit: asyncComponent({
        resolve: () => import("../../workflow/components/follow/tagEdit")
    }),
    WfFreeFlowSet: asyncComponent({
        resolve: () => import("./workflowfree/FlowSet.js")
    }),
    QYSAuth: asyncComponent({
        resolve: () => import("./secondauth/index")
    }),
    OdocComs: asyncComponent({
        resolve: () => import("../../odoc/OdocComs.js")
    }),
    EasyPicture: asyncComponent({
        resolve: () => import('./hoverRoute/EasyPicture')
    }),
    InvoicePage:asyncComponent({
        resolve:()=>import("./fnaPage/invoiceBrowser")
    })
    // FreeWorkflowSimple: asyncComponent({
    //     resolve: () => import("./hoverRoute/free-workflow-simple")
    // }),
}

@inject('wfGlobalStore', 'wfLayoutStore', 'wfRemindStore', 'secondAuthStore', 'wfCommunicateStore', 'wfSignListStore')
@withRouter
@observer
export default class Req extends React.Component {
    componentWillMount() {
        window.JS_LOAD_DURATION = new Date().getTime() - window.wm_test_body_js_start;
        AsyncUtil.loadResource();
    }
    componentWillReceiveProps(nextProps, nextState) {
        const location = this.props.location || {};
        const nextLocation = nextProps.location || {};
        const pathname = location.pathname || "";
        const nextPathname = nextLocation.pathname || "";
        console.log("Req componentWillReceiveProps", location, nextLocation);
        if (pathname !== nextPathname) {
            EmSDK.setReqEmTopNav(nextPathname);
            if (nextPathname == '/req')
                EmSDK.controlBottomBtn(nextPathname);
            //路由变化需控制缩放
            if (pathname !== nextPathname)
                FormUtil.controlViewPort(nextPathname);
            if (nextPathname === '/req/follow')
                this.props.history.push('/req/follow')
        }
    }
    componentDidMount() {
          this.doInit(this.props);
       
            window.lsxUpdatemark6=(logid)=>{
                const { wfLayoutStore,wfGlobalStore} = this.props;
                 const {propFileCfg={}}=wfLayoutStore;
                if(wfGlobalStore.requestType!=0&&propFileCfg&&propFileCfg.openSeeIncome==1){
                    let islsx6=wfGlobalStore.variableMap.get('islsx6');
                    if(islsx6!==1&&islsx6!==2){
    
                        if(!window['log6_count_'+logid]){
                            window['log6_count_'+logid]=1;
                        }else{
                            window['log6_count_'+logid]++;
                        }
    
                        setTimeout(() => {
                            window['log6_count_'+logid]=0;
                        }, 300);
                        
                        if(window['log6_count_'+logid]>1){
                            window.lsxlogid=logid;
                            window.newRemark='';
                            const { logidMap={}}=propFileCfg;
                            wfGlobalStore.controlVariableMap('islsx6',2);
                            document.getElementById('log_del_'+logid).style.display="none";
                            try{
                                let p= document.getElementById('log_del_'+logid).nextElementSibling;
                                if(p&&p.tagName=='P'){
                                    p.style.display="none";
                                }
                            }catch(e){
                                if(window.console)
                                console.log(e);
                            }
                            if(window['log6_update_'+logid]===1){
                                document.getElementById('log6_update_'+logid).style.display="block";
                            }else{
                                window['log6_update_'+logid]=1;
                                ReactDOM.render(<CusSignInputNew wfLayoutStore={wfLayoutStore} wfGlobalStore={wfGlobalStore} isadd={2} logid={logid} remark={logidMap[logid]} />, document.getElementById('log6_update_'+logid));
                            }
                            setTimeout(() => {
                                wfform.getGlobalStore().richEditorStore.editor.focusManager.focus();
                            }, 300);
                        }
                       
                    }
                    
                }
            }
         
       
        // jQuery("body").click(function(e){
        //     try{
        //         if(wfGlobalStore.variableMap.has('islsx6')){
                   
        //             let islsx6=wfGlobalStore.variableMap.get('islsx6');
        //             if(islsx6>0){
        //                 let needHide=true;
        //                 let myRemarkAdd=document.getElementById('myRemarkAdd');
        //                  if (myRemarkAdd&&e.target.compareDocumentPosition(myRemarkAdd) === 10) {
        //                     needHide=false;
        //                 }
        //                 if(needHide){
        //                     let ckDiv=document.getElementById('ck_rich_text_default_font');
        //                     if(ckDiv&&e.target.compareDocumentPosition(ckDiv) === 10){
        //                         needHide=false;
        //                     }
        //                 }

        //                 // if(needHide){
        //                 //     let ckDiv=document.getElementById('needAdd');
        //                 //     if(ckDiv&&e.target.compareDocumentPosition(ckDiv) === 10){
        //                 //         needHide=false;
        //                 //     }
        //                 // }
        //                 if(needHide){
        //                     //wfGlobalStore.controlVariableMap('islsx6',0);
        //                 }
        //             }
        //         }
        //     }catch(e){
        //         if(window.console){
        //             console.log(e);
        //         }
        //     }
        // });
    }
    componentWillUnmount() {
        console.log("Req componentWillUnmount");
        this.doClear();
    }
    doInit(props) {
        const { wfGlobalStore, wfLayoutStore, location } = props;
        //监听器调试用
        // const disposer = observe(wfGlobalStore, "loading", change =>{
        //     console.log("observe change", change);
        // });
        let queryParams = ForwardPage.transQueryParams(location);
        wfGlobalStore.loadBaseInfo(queryParams);
        //绑定source
        src.setIsMobile(true);
        src.init(wfGlobalStore, wfLayoutStore, FieldEntity, API_REQ, getLabel);
    }
    doClear() {
        const { wfGlobalStore } = this.props;
        wfGlobalStore.resetAllFormState();
        InvoiceUtil.unbindOnMessage();
    }
    getPage(tabkey, tabs) {
        let page = 0;
        tabs.map((item, index) => {
            if (item.id == tabkey) {
                page = index;
            }
        })
        return page;
    }
    render() {
        const { wfGlobalStore, wfLayoutStore, wfRemindStore, secondAuthStore, wfCommunicateStore, location, history, wfSignListStore: { showReply } } = this.props;
        const { tabKey, commonParam, variableMap, promptInfos = [], urlParams, secondAuthInfo, continuationProcessInfo } = wfGlobalStore;
        const { hasNewCommunication, isOpenCommunication, showFreeWfSimpleCom, isHideArea } = commonParam;
        const { setSignReply, clearReplyInfo, signReplyInfo, setTabKey, controlVariableMap } = wfGlobalStore;
        const { comSetStoreState } = wfCommunicateStore;
        const { dialogVisible } = secondAuthStore;
        const { odocInfo = {} } = wfLayoutStore;
        const { mobileInfo = {}, mobile_odoc_hidwfbtn = false } = odocInfo;
        const { isShowDocTab } = mobileInfo;
        const forceRender = variableMap.get("forceRenderReq") || 0;    //勿刪
        const helpfulTipVisiable = variableMap.get("helpful-tip-visiable") || false;
        if (variableMap.get("verifyRight") === false)
            return <ReqNoRight {...toJS(variableMap.get("noRightProps"))} />
        //将Tab项及下拉项统一放置此处，往PC端靠拢，满足拦截事件重排序命名功能，渲染时再从此对象过滤遍历取值
        let tabDatas = [];
        //默认Tab项 
        tabDatas.push({ title: getLabel(34130, '流程表单'), key: "layout", type: 1 });
        isHideArea != undefined && isHideArea != "1" && tabDatas.push({ title: getLabel(125734, "流转意见"), key: "signlist", type: 1 });
        isOpenCommunication && tabDatas.push({ title: getLabel(512444, "相关交流"), key: "communicate", type: 1 });
        isShowDocTab && tabDatas.push({ title: getLabel(1265, "正  文"), key: "odoc", type: 1 });
        if (variableMap.has('customTabs')) {
            let customTabs = toJS(variableMap.get('customTabs')) || [];
            customTabs.forEach(item => {
                tabDatas.push({ title: item.title, key: item.id, type: 1 });
            });
        }
        //默认右上角下拉项
        if (window.location.href.indexOf("hidePicture") === -1)
            tabDatas.push({ title: getLabel(18912, "流程图"), key: "picture", type: 2 });
        tabDatas.push({ title: getLabel(386192, "流程状态"), key: "status", type: 2 });
        tabDatas.push({ title: getLabel(386426, "相关资源"), key: "resource", type: 2 });
        if (variableMap.has('customDrops')) {
            let customDrops = toJS(variableMap.get('customDrops')) || [];
            customDrops.forEach(item => {
                tabDatas.push({ title: item.title, key: item.key, type: 2 });
            });
        }
        //允许拦截接口做排序、重命名
        typeof window.WfForm.overrideTabDatas === "function" && (tabDatas = window.WfForm.overrideTabDatas(tabDatas));
        //tabDatas.push({ title: "附件", key: "ReqWffileUpload", type: 1 });
        let reqWffilefieldid = '';
        //分发Tab及下拉
        const tabs = tabDatas.filter(item => (item.type === 1 && item.key != "signlist")).map(item => {
            let titleNew = <span>{item.title}</span>;
            if (item.key === "communicate"){
                titleNew = hasNewCommunication ? <Badge dot><span>{getLabel(512444, "相关交流")}</span></Badge > : <span>{getLabel(512444, "相关交流")}</span>;
            }
            if (item.tabType == 3 && item.url.indexOf("/main/workflow/wffileupload") != -1){
                let str=item.url;
                let str2=str.substring(str.indexOf('fieldid=')+8);

                if(str2.indexOf('&')==-1){
                    reqWffilefieldid=str2.substring(str2.indexOf('&'));
                }else{
                    reqWffilefieldid=str2.substring(0,str2.indexOf('&'));
                }
                return { id: "ReqWffileUpload", title: titleNew };
            }
            return { id: item.key, title: titleNew };
        });
        const Item = Popover.Item;
        const overlayItem = tabDatas.filter(item => item.type === 2).map(item => {
            return <Item key={item.key}>{item.title}</Item>;
        });
        //生成Tab组件对象
        let tabBtns = [];
        const tabProps = {
            onTabClick: (tab) => {
                this.switchTab(1, tab.id);
                comSetStoreState({ needPanel: false });
            },
            page: this.getPage(tabKey, tabs)
        };
        //生成下拉组件对象
        const popoverPropsVisiable = variableMap.get('popoverPropsVisiable')
        let popoverProps = {
            overlayClassName: "wf-req-top-popover",
            overlay: overlayItem,
            visible: popoverPropsVisiable || false,
            onVisibleChange: (visible) => {
                controlVariableMap("popoverPropsVisiable", visible)
            },
            onSelect: (node, index) => {
                controlVariableMap("popoverPropsVisiable", false);
                this.switchTab(2, node.key);
            }
        };

        if (location.pathname !== "/req")
            popoverProps["visible"] = false;
        const { dataJson } = wfLayoutStore;
        const hasLoad = !_.isEmpty(commonParam) && !_.isEmpty(dataJson);
        const { requestType, showLayoutSwitch, layoutAnalysisType } = commonParam;
        if (!_.isEmpty(commonParam) && showLayoutSwitch === 1) {
            tabBtns.push([
                <div className="wf-req-switch-pc" onClick={this.switchPcLayout.bind(this)}>
                    <Icon type={layoutAnalysisType == "2" ? "sault" : "pc"} />
                </div>
            ]);
        }
        const showPrompt = hasLoad && promptInfos.length > 0 && tabKey === "layout";
        const showAuthInfo = hasLoad && !_.isEmpty(secondAuthInfo) && tabKey == "layout";
        const { remindInfo } = wfRemindStore;
        const showRemindInfo = hasLoad && !_.isEmpty(remindInfo) && remindInfo.isShow === true;
        const themeVars = window.getThemeVars();
        const { hd = 1 } = themeVars;
        let reqMainStyle = {
            paddingBottom: !showReply && (tabKey === "layout" || tabKey === "signlist") ? calcReqMainPaadingBottom() : '0px'
        }
        //快速处理功能条，设置req-main的高度
        if (continuationProcessInfo.loaded) {
            reqMainStyle.height = `calc(100% - ${hd * 45}px)`;
        }

        return (
            <Fragment> 
                <div className="wf-req">

                    {/* 流程连续处理功能条 */}
                    {
                        continuationProcessInfo.loaded && <ContinuationProcess continuationProcessInfo={continuationProcessInfo} />
                    }

                    <div className="wf-req-main" style={reqMainStyle} >

                        <div className="wf-req-top">
                            <TabPage
                                tabs={tabs} btns={tabBtns} span={2}
                                tabProps={tabProps} popover popoverProps={popoverProps}
                            />

                        </div>
                        <div className="wf-req-content" onScroll={this.doScrollEvent.bind(this)}>
                            <div className="wf-req-form" style={{ display: tabKey === "layout" ? "block" : "none" }}>
                                <WhiteSpace />
                                {
                                    showAuthInfo &&
                                    [<SecondAuthInfo {...toJS(secondAuthInfo)} openAuthDetail={openAuthDetail} />, <WhiteSpace />]
                                }
                                {
                                    showPrompt &&
                                    [<Prompt promptInfos={promptInfos} />, <WhiteSpace />]
                                }
                                {
                                    showRemindInfo &&
                                    [<RemindType className="wf-submit-remind-type" />, <WhiteSpace />]
                                }
                                <div className="wf-req-layout">
                                    {
                                        hasLoad && <MainLayout symbol="main" />
                                    }
                                </div>
                                <WhiteSpace />
                            </div>
                            {hasLoad && showFreeWfSimpleCom == 1 && <div className="wf-freeworkflow-simple" style={{ display: tabKey === "layout" ? "block" : "none" }}>
                                {[<FreeWorkflowSimple />, <WhiteSpace />]}
                            </div>}
                            {hasLoad && <div className="wf-req-fileUpload" style={{ display: tabKey === "ReqWffileUpload" ? "block" : "none" }}>
                                {reqWffilefieldid != '' && <ReqWffileUpload fieldid={reqWffilefieldid} wfLayoutStore={wfLayoutStore} wfGlobalStore={wfGlobalStore} />}
                            </div>}
                            <div className={`wf-req-signlist ${tabKey === 'signlist' ? 'wf-req-signlist-tab' : ''}`} style={{ display: (tabKey === 'signlist' || tabKey === 'layout') ? "block" : "none" }}>
                                {hasLoad && requestType != 2 && isHideArea != "1" &&
                                    <div className={`wf-req-form-signlist-title`}
                                        style={{ display: tabKey === "layout" ? "block" : "none" }}>
                                        <span>{getLabel(125734, "流转意见")}</span>
                                    </div>
                                }
                                {
                                    hasLoad && requestType != 2 && isHideArea != "1" && <SignList comSetStoreState={comSetStoreState} setTabKey={setTabKey} setSignReply={setSignReply} params={commonParam} reqUrlParams={urlParams} />
                                }
                            </div>
                            <div className={`wf-req-communicate ${tabKey === 'communicate' ? 'wf-req-communicate-tab' : ''}`} >
                                {
                                    hasLoad && tabKey === 'communicate' && <Communicate clearReplyInfo={clearReplyInfo} signReplyInfo={signReplyInfo}  commonParams={commonParam}/>
                                }
                            </div>
                            <div className={`wf-req-odoc ${tabKey === 'odoc' ? 'wf-req-odoc-tab' : ''}`} style={{ display: (tabKey === 'odoc') ? "block" : "none" }}>
                                <OdocPage />
                            </div>
                            <div className='wf-append-iframe' style={{ display: tabKey.indexOf('custom_iframe_') > -1 ? 'block' : 'none' }}>
                                <iframe className='custom-tab-iframe' src='' style={{ border: 0, width: '100%', height: '100%' }}></iframe>
                            </div>
                        </div>
                        <div className="wf-req-bottom" style={{ display: (tabKey === "communicate") ? "none" : "block" }}>
                            {hasLoad && tabKey !== 'communicate' && (tabKey == "odoc" && mobile_odoc_hidwfbtn == true ? false : true) && <BottomOperate />}
                        </div>

                    </div>
                    {
                        hasLoad && this.generateRouteLayout()
                    }
                    {
                        hasLoad && variableMap.has('reqImportStore') && <ReqImport />
                    }
                    {
                        hasLoad && variableMap.has('dingStore') && <ReqDing />
                    }
                

                    {
                        dialogVisible.has(authTypes.SECOND_AUTH_DIALOG) &&
                        <SecondAuthDialog
                            visible={dialogVisible.get(authTypes.SECOND_AUTH_DIALOG)} />
                    }

                </div>
                { helpfulTipVisiable && <WfHelpefulTipContent/> }
            </Fragment>
        )
    }
    generateRouteLayout() {
        let arr = [];
        const { baseParam, commonParam} = this.props.wfGlobalStore;
        const { fnaInfo } = this.props.wfLayoutStore;
        const picParams = { ...baseParam, ...commonParam };
        const map = {
            "editDetailRow": <coms.EditDetailRow />,
            "picture": <coms.Picture params={{ ...picParams, isReadOnlyModel: 'true' }} />,
            "status": <coms.Status params={baseParam} />,
            "resource": <coms.Resource params={commonParam} />,
            "ehOperator": <coms.EhOperator />,
            "reject": <coms.RejectChoose />,
            "forwardback": <coms.ForwardBack params={baseParam} />,
            "annexList": <coms.SignAnnexList />,
            "soundList": <coms.SignSoundList />,
            "formAnnotationList": <coms.SignFormAnnotationList />,
            "share": <Share
                msgInfo={base.wfOperateStore.msgInfo}
                shareParams={base.wfOperateStore.shareParams}
                store={base.wfOperateStore.share}
            // browserConfig={base.wfOperateStore.browserConfig}
            />,
            "nextNodeOperator": <coms.NextNodeOperator />,
            "easyPicture": <coms.EasyPicture params={{ ...picParams, isReadOnlyModel: 'true' }}/>,
            "locationMap": <coms.LocationMap />,
            "intervenor": <coms.Intervenor />,
            "fnaInvoiceScanning": <coms.FnaInvoiceScanning
                fnaInfo={fnaInfo}
                baseParam={baseParam}
                commonParam={commonParam} />,//财务发票扫描
            "secondAuthDetail": <coms.SecondAuthDetail />,
            "secondAuthCert": <coms.SecondAuthDetail />,
            "reminderConfirm": <coms.ConfirmReminder />,
            'follow': <coms.FollowList store={base.wfOperateStore} type={'detailpage'} />,
            'tagManage': <coms.TagManage store={base.wfOperateStore} type={'detailpage'} />,
            'tagEdit': <coms.TagEdit store={base.wfOperateStore} type={'detailpage'} />,
            "wfFreeFlowSet": <coms.WfFreeFlowSet params={{ ...picParams, isReadOnlyModel: 'false' }} />,
            "qysauth": <coms.QYSAuth ctype={1} />,
            "odocComs": <coms.OdocComs />,
            "InvoicePage": <coms.InvoicePage />,
            'map': <coms.Map location={this.props.location}/>
        };
        Object.keys(map).forEach(key => {
            arr.push(
                <Route key={key} path={`/req/${key}`} render={() => {
                    return <RouteLayout>
                        <div key={key} className="wm-route-layout">{map[key]}</div>
                    </RouteLayout>
                }}></Route>
            );
        });
        return arr;
    }
    switchTab = (type, tabKey) => {    //type为1代表Tab切换，为2代表下拉切换
        FormUtil.switchTabFun(tabKey,type);
    }
    switchPcLayout() {
        Common.showConfirm({
            title: getLabel(500269, "当前数据未保存，是否切换显示模式？"),
            okEvent: () => {
                const { urlParams, commonParam } = this.props.wfGlobalStore;
                const newParams = { ...urlParams, ...{ layoutAnalysisType: commonParam.layoutAnalysisType == "2" ? "1" : "2" } };
                FormUtil.reloadFormPage(newParams);
            }
        });
    }
    doScrollEvent() {
        const { wfGlobalStore } = this.props;
        const { tabKey } = wfGlobalStore;
        window.formImgLazyLoad(jQuery(".wf-req-content"));
        DetailUtil.fixedDetailHead();
        DetailUtil.controlSlidePrompt();
        window.WfForm.triggerScrollEvent();
        loadMoreSign();
    }
}